<template>
  <div>
    <!-- 下拉刷新 -->
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh" :disabled ="finished">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :immediate-check="false"
      >
        <!-- 循环渲染文章的列表 -->
        <ArtItem
          v-for="item in artlist"
          :key="item.id"
          :article="item"
          @remove-article="removeArticle"
        ></ArtItem>
      </van-list>
    </van-pull-refresh> 
  </div>
</template>

<script>
import { getArtListAPI } from "../api/homeAPI";
import ArtItem from "./ArtItem.vue";

export default {
  // 大驼峰命名法：每个单词的首字母大写
  name: "ArticleList",
  data() {
    return {
      artlist: [],
      timestamp: Date.now(),
      loading: false,
      finished: false,
      isLoading: false,
    };
  },
  props: {
    channelId: {
      type: Number,
      required: true,
    },
  },
  components: {
    getArtListAPI,
    ArtItem,
  },
  methods: {
    async initArtList(isRefresh) {
      const { data: res } = await getArtListAPI(this.channelId, this.timestamp);
      if (res.message === "OK") {
        this.timestamp = res.data.pre_timestamp;
        
        if(isRefresh) {
          this.artlist = [ ...res.data.results,...this.artlist];
          this.isLoading = false
        }else {
          this.artlist = [...this.artlist, ...res.data.results];
          this.loading = false;
        }
        if (this.timestamp === null) {
          this.finished = true;
        }
      }
    },
    onLoad() {
      console.log('触发了上拉刷新')
      this.initArtList(false);
    },
    onRefresh () {
      console.log('触发了下拉刷新')
      this.initArtList(true)
    },
    removeArticle(id){
      this.artlist = this.artlist.filter(item => item.art_id !== id)
      if(this.artlist.length < 10){
        this.initArtList(false)
      }
    }
  },
  created() {
    this.initArtList();
  },
};
</script>

<style lang="less" scoped></style>
